package com.artup.service.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.artup.common.Constants;
import com.artup.common.ResponseResult;
import com.artup.dao.MaterialDao;
import com.artup.dao.MaterialEditDao;
import com.artup.dao.OrderWorksRelationDao;
import com.artup.dao.SkuDao;
import com.artup.dao.WorksDao;
import com.artup.pojo.Material;
import com.artup.pojo.MaterialEdit;
import com.artup.pojo.Works;
import com.artup.service.WorksService;
import com.artup.util.CommonUtils;
import com.artup.util.file.FolderUtils;
import com.artup.util.file.PropertiesUtils;
import com.artup.util.image.ImageUtil;
import com.artup.util.os.OperationSystemInfo;
import com.artup.util.pdf.PdfUtil;
import com.artup.util.shell.ChmodShell;
import com.artup.vo.WorksVo;

@Service( value = "worksService" )
public class WorksServiceImpl implements WorksService {
	protected static final Logger LOGGER = LoggerFactory.getLogger(WorksServiceImpl.class);
	
	private final int WORKS_BOX_WIDTH = 968;		// 作品框的宽度（单位：像素）
	private final int WORKS_BOX_HEIGHT = 1482;		// 作品框的高度（单位：像素）

	@Autowired
	private WorksDao worksDao;
	
	@Autowired
	private MaterialDao materialDao;
	
	@Autowired
	private SkuDao skuDao;
	
	@Autowired
	private MaterialEditDao materialEditDao;

	@Autowired
	private OrderWorksRelationDao orderWorksRelationDao;

	@Override
	public ResponseResult queryWorksById(String id) {
		LOGGER.info("id = {}", id);
		
		ResponseResult responseResult = new ResponseResult();
		
		if(StringUtils.isBlank(id)) {
			responseResult.setStatus(Constants.ACTION_STATUS_PARAMETER_EMPTY);
			responseResult.setMessage("【ID】不可为空！");
			
			return responseResult;
		}
		
		Works works = null;
		try {
			works = this.worksDao.selectWorksById(id);
		} catch (SQLException e) {
			LOGGER.error("根据【ID】查询【作品】 - 失败！", e);
			
			responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
			responseResult.setMessage("根据【ID】查询【作品】 - 失败！");
			
			return responseResult;
		}
		
		if(null != works) {
			WorksVo worksVo = new WorksVo();
			worksVo.setId(works.getId());
			worksVo.setPassportId(works.getPassportId());
			worksVo.setName(works.getName());
			worksVo.setPrice(works.getPrice());
			worksVo.setQuantity(works.getQuantity());
			worksVo.setSize(works.getSize());
			worksVo.setShape(works.getShape());
			worksVo.setColor(works.getColor());
			worksVo.setTypeCode(works.getTypeCode());
			worksVo.setStatus(works.getStatus());
			worksVo.setThumbnailId(works.getThumbnailId());
			worksVo.setSkuCode(works.getSkuCode());
			worksVo.setFinishTime(works.getFinishTime());
			worksVo.setCreateTime(CommonUtils.dateFormat(works.getCreateTime(), "yyyy-MM-dd HH:mm"));
			
			if(StringUtils.isNotBlank(works.getThumbnailPath())) {
				String worksThumbnailPath = works.getThumbnailPath();
				
				int worksThumbnailIndex = worksThumbnailPath.indexOf("edited");
				if(0 < worksThumbnailIndex) {
					worksVo.setThumbnailPath(PropertiesUtils.getValue("artup.mobile.url.perfix") + worksThumbnailPath.substring(worksThumbnailIndex, worksThumbnailPath.length()));
				}
			}

			responseResult.setData(worksVo);
		}
		
		responseResult.setStatus(Constants.ACTION_STATUS_SUCCESS);
		responseResult.setMessage("查询【作品】 - 成功。");
		
		return responseResult;
	}

	@Override
	public ResponseResult batchDeleteWorksByIds(Integer passportId, String ids) {
		LOGGER.info("passportId = {}, ids = {}", passportId, ids);
		
		ResponseResult responseResult = new ResponseResult();
		
		if(StringUtils.isBlank(ids)) {
			responseResult.setStatus(Constants.ACTION_STATUS_PARAMETER_EMPTY);
			responseResult.setMessage("无参数！");
			
			return responseResult;
		} else if(null == passportId) {
			responseResult.setStatus(Constants.ACTION_STATUS_PARAMETER_EMPTY);
			responseResult.setMessage("【通行证ID】不可为空！");
			
			return responseResult;
		} else if(0 >= passportId) {
			responseResult.setStatus(Constants.ACTION_STATUS_PARAMETER_NOT_POSITIVE_INTEGER);
			responseResult.setMessage("【通行证ID】为正整数！");
			
			return responseResult;
		}
		
		int orderWorksRelationCount = 0;
		try {
			orderWorksRelationCount = this.orderWorksRelationDao.selectOrderWorksRelationCountByWorksIds(ids.split(","), passportId);
		} catch (SQLException e) {
			LOGGER.error("根据【作品IDs】查询【订单与作品关系数】 - 失败！", e);
			
			responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
			responseResult.setMessage("根据【作品IDs】查询【订单与作品关系数】 - 失败！");
			
			return responseResult;
		}
		
		if(0 < orderWorksRelationCount){
			responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
			responseResult.setMessage("含有已下单或已加入购物车的作品，无法删除！");
			
			return responseResult;
		}
		
		try {
			this.materialEditDao.batchDeleteMaterialEditByWorksIds(ids.split(","));
		} catch (SQLException e) {
			LOGGER.error("根据【作品IDs】批量删除【素材编辑】 - 失败！", e);
			
			responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
			responseResult.setMessage("根据【作品IDs】批量删除【素材编辑】 - 失败！");
			
			return responseResult;
		}
		
		try {
			this.worksDao.batchDeleteWorksByIds(ids.split(","));
		} catch (SQLException e) {
			LOGGER.error("根据【IDs】批量删除【作品】 - 失败！", e);
			
			responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
			responseResult.setMessage("根据【IDs】批量删除【作品】 - 失败！");
			
			return responseResult;
		}
		
		responseResult.setStatus(Constants.ACTION_STATUS_SUCCESS);
		responseResult.setMessage("根据【IDs】批量删除【作品】 - 成功。");
		
		return responseResult;
	}
	
	@Override
	public ResponseResult saveWorks(String worksJSONObject) {
		LOGGER.info("worksJSONObject = {}", worksJSONObject);
		
		ResponseResult responseResult = new ResponseResult();
		
		if(StringUtils.isBlank(worksJSONObject)) {
			responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
			responseResult.setMessage("无参数！");
			
			return responseResult;
		}
		
		JSONObject worksJSONObject_ = JSONObject.parseObject(worksJSONObject);
		
		Works works = new Works();	// 作品
		String worksId = CommonUtils.UUIDGenerator(); 	// 作品ID
		works.setId(worksId);
		works.setStatus((byte) 2);
		
		String skuCode2 = null;		// 编辑完成后重新选择框型的 SKUCode
		
		if(worksJSONObject_.containsKey("passportId")) {
			works.setPassportId(worksJSONObject_.getIntValue("passportId"));
		}
		
		if(worksJSONObject_.containsKey("worksName")) {
			works.setName(worksJSONObject_.getString("worksName"));
		}
		if(worksJSONObject_.containsKey("worksSize")) {
			works.setSize(worksJSONObject_.getString("worksSize"));
		}
		if(worksJSONObject_.containsKey("worksQuantity")) {
			works.setQuantity(worksJSONObject_.getIntValue("worksQuantity"));
		}
		if(worksJSONObject_.containsKey("worksTypeCode")) {
			works.setTypeCode(worksJSONObject_.getString("worksTypeCode"));
		}
		if(worksJSONObject_.containsKey("worksShape")) {
			works.setShape(worksJSONObject_.getString("worksShape"));
		}
		if(worksJSONObject_.containsKey("worksColor")) {
			works.setColor(worksJSONObject_.getString("worksColor"));
		}
		if(worksJSONObject_.containsKey("worksSize")) {
			works.setSize(worksJSONObject_.getString("worksSize"));
		}
		if(worksJSONObject_.containsKey("worksThumbnailId")) {
			works.setThumbnailId(worksJSONObject_.getString("worksThumbnailId"));
		}
		if(!worksJSONObject_.containsKey("worksChannelCode") || StringUtils.isBlank(worksJSONObject_.getString("worksChannelCode"))) {
			works.setChannelCode("artron");
		} else {
			works.setChannelCode(worksJSONObject_.getString("worksChannelCode"));
		}
		if(!worksJSONObject_.containsKey("worksClientCode") || StringUtils.isBlank(worksJSONObject_.getString("worksClientCode"))) {
			works.setClientCode("ios");
		} else {
			works.setClientCode(worksJSONObject_.getString("worksClientCode"));
		}
		if(worksJSONObject_.containsKey("skuCode")) {
			works.setSkuCode(worksJSONObject_.getString("skuCode"));
		}
		if(worksJSONObject_.containsKey("skuCode2")) {
			skuCode2 = worksJSONObject_.getString("skuCode2");
		}
		if(worksJSONObject_.containsKey("materialId")) {
			String materialId = worksJSONObject_.getString("materialId");
			works.setThumbnailId(materialId);
			
			String thumbnailPath = "";		// 缩略图路径
			try {
				thumbnailPath = this.materialDao.selectMaterialThumbnailPath(materialId);
			} catch (SQLException e) {
				LOGGER.error("根据【ID】查询【素材缩略图路径】 - 失败！");
				
				responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
				responseResult.setMessage("根据【ID】查询【素材缩略图路径】 - 失败！");
				
				return responseResult;
			}
			
			works.setThumbnailPath(thumbnailPath);	
		}
		if(StringUtils.isNotBlank(works.getTypeCode()) && StringUtils.isNotBlank(works.getSize())) {
			works.setTemplateId(works.getTypeCode() + "_" + works.getSize());
		}
		
		Float serverPrice = null;
		try {
			serverPrice = this.skuDao.selectPriceByCode(works.getSkuCode());
		} catch (Exception e) {
			LOGGER.error("根据【编号】查询【单价】 - 失败！", e);
			
			responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
			responseResult.setMessage("根据【编号】查询【单价】 - 失败！");
			
			return responseResult;
		}
		
		if(null != serverPrice) {
			works.setPrice(serverPrice);
		}
		
		if(worksJSONObject_.containsKey("materialEdit") && StringUtils.isNotBlank(worksJSONObject_.getString("materialEdit"))) {
			JSONArray materialEditJSONArray = JSONArray.parseArray(worksJSONObject_.getString("materialEdit"));
			
			if(null != materialEditJSONArray) {
				for(int cursor = 0; cursor < materialEditJSONArray.size(); cursor++) {
					JSONObject materialEditJSONObject = materialEditJSONArray.getJSONObject(cursor);
					
					if(null == materialEditJSONObject) {
						continue;
					}
					
					MaterialEdit materialEdit = new MaterialEdit();
					String worksEditId = CommonUtils.UUIDGenerator();
					materialEdit.setId(worksEditId);
					materialEdit.setWorksId(worksId);
					materialEdit.setStatus((byte) 1);
					
//					Material material = null;
					
					if(materialEditJSONObject.containsKey("materialId")) {
						if(StringUtils.isNotBlank(materialEditJSONObject.getString("materialId"))) {
							materialEdit.setMaterialId(materialEditJSONObject.getString("materialId"));
							
							/*try {
								material = this.materialDao.selectMaterialById(materialEditJSONObject.getString("materialId"));
							} catch (SQLException e) {
								LOGGER.error("根据【ID】查询【素材】 - 失败！", e);
								
								responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
								responseResult.setMessage("根据【ID】查询【素材】 - 失败！");
								
								return responseResult;
							}*/
						}
					}
					
					int x_cut = 0;	// X 起始坐标
					int y_cut = 0;	// Y 起始坐标
					int width_cut = 0;	// （裁切）宽度
					int height_cut = 0;	// （裁切）高度
					int rotate = 0;		// 旋转的角度
					float scale = 1;	// 放大或缩小的倍数
					/*
					String orignalStoragePath = null;	// 原图路径
					String rotatedImagePath = null;		// 旋转后的图片路径
					String cutedImagePath = null;		// 裁切后的图片路径
					String worksImagePath = null;		// 作品图片路径
					
					if(null != material) {
						orignalStoragePath = material.getOrignalStoragePath();
						
						if(StringUtils.isNotBlank(orignalStoragePath)){
							String expandedName = orignalStoragePath.substring(orignalStoragePath.lastIndexOf("."), orignalStoragePath.length());
							
							String rotatedSystemFileName = CommonUtils.UUIDGenerator() + expandedName;	// 旋转后的系统文件名
							String cutedSystemFileName = CommonUtils.UUIDGenerator() + expandedName;	// 裁切后的系统文件名
							String worksSystemFileName = CommonUtils.UUIDGenerator() + expandedName;	// 裁切后的系统文件名
							
							String rotatedImagePrefix = PropertiesUtils.getValue("works.image.edited.rotated.path");
							String cutedImagePrefix = PropertiesUtils.getValue("works.image.edited.cuted.path");
							String worksImagePrefix = PropertiesUtils.getValue("works.image.edited.final.path");
							
							rotatedImagePath = FolderUtils.getStoragePath(rotatedImagePrefix, works.getPassportId()) + rotatedSystemFileName;
							cutedImagePath = FolderUtils.getStoragePath(cutedImagePrefix, works.getPassportId()) + cutedSystemFileName;
							worksImagePath = FolderUtils.getStoragePath(worksImagePrefix, works.getPassportId()) + worksSystemFileName;
						}
						
						if(StringUtils.isNotBlank(material.getSmallThumbnailImagePath())) {
							works.setThumbnailPath(material.getSmallThumbnailImagePath());
						}
					}*/
					
					if(materialEditJSONObject.containsKey("materialIndex")) {
						if(0 < materialEditJSONObject.getInteger("materialIndex")) {
							materialEdit.setMaterialIndex(materialEditJSONObject.getInteger("materialIndex"));
						}
					}
					
					JSONObject actionJSONObject = new JSONObject();		// 动作/操作步骤
					
					if(materialEditJSONObject.containsKey("x")) {
						x_cut = materialEditJSONObject.getIntValue("x");
						LOGGER.debug("x_cut = {}", x_cut);
						
						actionJSONObject.put("x", x_cut);
					}
					if(materialEditJSONObject.containsKey("y")) {
						y_cut = materialEditJSONObject.getIntValue("y");
						LOGGER.debug("y_cut = {}", y_cut);
						
						actionJSONObject.put("y", y_cut);
					}
					if(materialEditJSONObject.containsKey("width")) {
						width_cut = materialEditJSONObject.getIntValue("width");
						LOGGER.debug("width_cut = {}", width_cut);
						
						actionJSONObject.put("width", width_cut);
					}
					if(materialEditJSONObject.containsKey("height")) {
						height_cut = materialEditJSONObject.getIntValue("height");
						LOGGER.debug("height_cut = {}", height_cut);
						
						actionJSONObject.put("height", height_cut);
					}
					if(materialEditJSONObject.containsKey("rotate")) {	// 旋转
						rotate = materialEditJSONObject.getIntValue("rotate");
						actionJSONObject.put("rotate", rotate);
						
						/*if(StringUtils.isNotBlank(orignalStoragePath)){
							boolean isRotateSuccess = ImageUtil.rotate(orignalStoragePath, rotatedImagePath, materialEditJSONObject.getIntValue("rotate"));
							if(isRotateSuccess) {
								materialEdit.setEditedMaterialPath(rotatedImagePath);
							}
						}*/
						LOGGER.debug("rotate = {}", rotate);
					}
					
					if(materialEditJSONObject.containsKey("scale")) {	// 放大/缩小
						scale = materialEditJSONObject.getFloat("scale");
						
						actionJSONObject.put("scale", scale);
						LOGGER.debug("scale = {}", scale);
					}
					
					/*LOGGER.debug("================== 裁剪 - 开始 ================");
					boolean isCutSuccess = ImageUtil.cutImage(rotatedImagePath, cutedImagePath, x_cut, y_cut, (int) (width_cut * scale), (int) (height_cut * scale));
					LOGGER.debug("以左上角为原点，从横坐标为：{}，纵坐标为：{} 开始裁切，裁切宽度为：{} 像素，裁切高度为：{} 像素。", x_cut, y_cut, (int) (width_cut * scale), (int) (height_cut * scale));
					LOGGER.debug("================== 裁剪 - 结束 ================");
					if(isCutSuccess) {
						int cutedWorksWidth = ImageUtil.getImageWidth(cutedImagePath);
						int cutedWorksHeight = ImageUtil.getImageHeight(cutedImagePath);
						
						*//**
						 * 以长边为基准进行缩放
						 *//*
						if(cutedWorksWidth >= cutedWorksHeight) {	// 以宽为基准进行缩放
							if(WORKS_BOX_WIDTH < cutedWorksWidth){
								cutedWorksWidth = WORKS_BOX_WIDTH;
								LOGGER.debug("以宽为基准进行缩放，缩放到：{} 像素。", cutedWorksWidth);
								
								boolean isZoomSuccess = ImageUtil.zoomImage(cutedImagePath, worksImagePath, cutedWorksWidth, null);
								if(isZoomSuccess) {
									cutedImagePath = worksImagePath;
								}
							}
						} else {	// 以高为基准进行缩放
							if(WORKS_BOX_HEIGHT < cutedWorksHeight) {
								cutedWorksHeight = WORKS_BOX_HEIGHT;
								LOGGER.debug("以高为基准进行缩放，缩放到：{} 像素。", cutedWorksHeight);
								
								boolean isZoomSuccess = ImageUtil.zoomImage(cutedImagePath, worksImagePath, null, cutedWorksHeight);
								if(isZoomSuccess) {
									cutedImagePath = worksImagePath;
								}
							}
						}
						
						materialEdit.setWidth(cutedWorksWidth);
						materialEdit.setHeight(cutedWorksHeight);
						
						materialEdit.setEditedMaterialPath(cutedImagePath);
					}*/
					
					this.buildPdfImage2(responseResult, materialEdit, works, x_cut, y_cut, width_cut, height_cut, rotate, scale, skuCode2);
					
					if(null != actionJSONObject) {
						materialEdit.setAction(actionJSONObject.toJSONString());
					}
					
					try {
						this.materialEditDao.insertMaterialEdit(materialEdit);
					} catch (Exception e) {
						LOGGER.error("添加【素材编辑】 - 失败！", e);
						
						responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
						responseResult.setMessage("添加【素材编辑】 - 失败！");
						
						return responseResult;
					}
				}
			}
		}
		
		try {
			this.worksDao.insertWorks(works);
		} catch (SQLException e) {
			LOGGER.error("添加【作品】 - 失败！");
			
			responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
			responseResult.setMessage("添加【作品】 - 失败！");
		}
		
		responseResult.setStatus(Constants.ACTION_STATUS_SUCCESS);
		responseResult.setMessage("保存【作品】 - 成功。");
		responseResult.setData(worksId);
		
		return responseResult;
	}
	
	@Override
	public ResponseResult queryWorksList(Works works) {
		LOGGER.info("works = {}", JSONObject.toJSONString(works));
		
		ResponseResult responseResult = new ResponseResult();
		
		if(null == works) {
			responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
			responseResult.setMessage("无参数！");
			return responseResult;
		}
		
		long totalCount = 0;
		try {
			totalCount = this.worksDao.selectWorksTotalCount(works);
		} catch (Exception e) {
			LOGGER.error("模糊查询【作品总记录数】 - 失败！", e);
			
			responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
			responseResult.setMessage("模糊查询【作品总记录数】 - 失败！");
			
			return responseResult;
		}
		
		Map<String, Object> resultMap = new HashMap<String, Object>();	// 结果集
		responseResult.setData(resultMap);
		resultMap.put("totalCount", totalCount);

		if(0 == totalCount) {
			responseResult.setStatus(Constants.ACTION_STATUS_SUCCESS);
			responseResult.setMessage("未找到作品！");
			
			return responseResult;
		}
		
		if(null == works.getPageIndex() || 0 >= works.getPageIndex()) {
			works.setPageIndex(1);
		}
		if(null == works.getPageSize() || 0 >= works.getPageSize()) {
			works.setPageSize(Integer.valueOf(PropertiesUtils.getValue("pagination.pageSize")));
		}
		
		long offset = (works.getPageIndex() - 1) * works.getPageSize();	// 起始订单行号
		
		works.setOffset(offset);
		
		List<Works> worksList = null;
		try {
			worksList = this.worksDao.selectWorksList(works);
		} catch (SQLException e) {
			LOGGER.error("模糊查询【作品列表】 - 失败！", e);
			
			responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
			responseResult.setMessage("模糊查询【作品列表】 - 失败！");
			
			return responseResult;
		}

		resultMap.put("worksList", null);
		
		if(CommonUtils.isNotEmpty(worksList)) {
			List<WorksVo> worksVoList = new ArrayList<WorksVo>();
			resultMap.put("worksList", worksVoList);
			
			for(int index = 0; index < worksList.size(); index++) {
				Works works_ = worksList.get(index);
				
				if(null == works_) {
					continue;
				}
			
				WorksVo worksVo = new WorksVo();
				worksVo.setId(works_.getId());
				worksVo.setPassportId(works_.getPassportId());
				worksVo.setName(works_.getName());
				worksVo.setPrice(works_.getPrice());
				worksVo.setQuantity(works_.getQuantity());
				worksVo.setSize(works_.getSize());
				worksVo.setColor(works_.getColor());
				worksVo.setShape(works_.getShape());
				if(StringUtils.isNotBlank(works_.getFinishTime())) {
					worksVo.setFinishTime(works_.getFinishTime().substring(0, 16));
				}
				worksVo.setCreateTime(CommonUtils.dateFormat(works_.getCreateTime(), "yyyy-MM-dd HH:mm"));
				if(StringUtils.isNotBlank(works_.getTypeCode())) {
					worksVo.setTypeCode(works_.getTypeCode());
					worksVo.setTypeName(Constants.WORKS_TYPE_MAP.get(works_.getTypeCode()));
				}
				worksVo.setStatus(works_.getStatus());
				if(1 == works_.getStatus()) {
					worksVo.setStatusName("未完成");
				} else if(2 == works_.getStatus()) {
					worksVo.setStatusName("已完成");
				}
				worksVo.setSkuCode(works_.getSkuCode());
				worksVo.setClientCode(works_.getClientCode());
				
				if(StringUtils.isNotBlank(works_.getThumbnailPath())) {
					String worksThumbnailPath = works_.getThumbnailPath();
					
					int worksThumbnailIndex = worksThumbnailPath.indexOf("edited");
					if(0 < worksThumbnailIndex) {
						worksVo.setThumbnailPath(PropertiesUtils.getValue("artup.mobile.url.perfix") + worksThumbnailPath.substring(worksThumbnailIndex, worksThumbnailPath.length()));
					}
				}
				
				worksVoList.add(worksVo);
			}
		}
		
		responseResult.setStatus(Constants.ACTION_STATUS_SUCCESS);
		responseResult.setMessage("查询【作品列表】 - 成功。");
		
		return responseResult;
	}

	@Override
	public ResponseResult queryTrolleyWorksCountByPassportId(Integer passportId) {
		LOGGER.info("passportId = {}", passportId);
		
		ResponseResult responseResult = new ResponseResult();
		
		if(null == passportId) {
			responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
			responseResult.setMessage("无参数！");
			return responseResult;
		}
		if(0 >= passportId) {
			responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
			responseResult.setMessage("无此会员！");
			return responseResult;
		}
		
		long trolleyWorksCount = 0;
		try {
			trolleyWorksCount = this.worksDao.selectTrolleyWorksCountByPassportId(passportId);
		} catch (Exception e) {
			LOGGER.error("根据【通行证ID】查询【购物车中作品】的数量 - 失败！", e);
			
			responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
			responseResult.setMessage("根据【通行证ID】查询【购物车中作品】的数量  - 失败！");
			
			return responseResult;
		}
		
		responseResult.setStatus(Constants.ACTION_STATUS_SUCCESS);
		responseResult.setMessage("查询【购物车中作品】的数量 - 成功。");
		responseResult.setData(trolleyWorksCount);
		
		return responseResult;
	}
	
	private ResponseResult buildPdfImage2(ResponseResult responseResult, MaterialEdit materialEdit, Works works, int abscissa, int ordinate, int width, int height, int rotate, float scale, String skuCode2) {
		LOGGER.info("abscissa = {}, ordinate = {}, width = {}, height = {}, rotate = {}, scale = {}, skuCode2 = {}", abscissa, ordinate, width, height, rotate, scale, skuCode2);
		
		Material material = null;
		try {
			material = this.materialDao.selectMaterialById(materialEdit.getMaterialId());
		} catch (SQLException e) {
			LOGGER.error("根据【ID】查询【素材】 - 失败！", e);
			
			responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
			responseResult.setMessage("根据【ID】查询【素材】 - 失败！");
			
			return responseResult;
		}
		
		if(null == material) {
			responseResult.setStatus(Constants.ACTION_STATUS_RESULT_EMPTY);
			responseResult.setMessage("未找到的【素材】！");
			
			return responseResult;
		}
		
		String orignalImagePath = material.getOrignalStoragePath();	// 原图路径
		
		if(StringUtils.isBlank(orignalImagePath)){
			responseResult.setStatus(Constants.ACTION_STATUS_RESULT_EMPTY);
			responseResult.setMessage("【素材无原图】！");
			
			return responseResult;
		}
		
		if(StringUtils.isNotBlank(material.getSmallThumbnailImagePath())) {
			works.setThumbnailPath(material.getSmallThumbnailImagePath());
		}
		
		String rotatedImagePath = null;		// 旋转后的图片路径
		String scaledImagePath = null;		// 旋转后的图片路径
		String cutedImagePath = null;		// 裁切后的图片路径
		String worksImagePath = null;		// 作品图片路径
		String worksThumbnailImagePath = null;		// 作品缩略图图路径
		
		String expandedName = orignalImagePath.substring(orignalImagePath.lastIndexOf("."), orignalImagePath.length());
		
		String rotatedSystemFileName = CommonUtils.UUIDGenerator() + expandedName;	// 旋转后的系统文件名
		String scaledSystemFileName = CommonUtils.UUIDGenerator() + expandedName;	// 缩放后的系统文件名
		String cutedSystemFileName = CommonUtils.UUIDGenerator() + expandedName;	// 裁切后的系统文件名
		String worksSystemFileName = CommonUtils.UUIDGenerator() + expandedName;	// 适应框型后的作品的系统文件名
		String worksThumbnailImageSystemFileName = CommonUtils.UUIDGenerator() + "_200" + expandedName;	// 裁切后的作品缩略图的系统文件名
		
		String rotatedImagePrefix = PropertiesUtils.getValue("works.image.edited.rotated.path");
		String scaledImagePrefix = PropertiesUtils.getValue("works.image.edited.scaled.path");
		String cutedImagePrefix = PropertiesUtils.getValue("works.image.edited.cuted.path");
		String worksImagePrefix = PropertiesUtils.getValue("works.image.edited.final.path");
		
		rotatedImagePath = FolderUtils.getStoragePath(rotatedImagePrefix, works.getPassportId()) + rotatedSystemFileName;
		scaledImagePath = FolderUtils.getStoragePath(scaledImagePrefix, works.getPassportId()) + scaledSystemFileName;
		cutedImagePath = FolderUtils.getStoragePath(cutedImagePrefix, works.getPassportId()) + cutedSystemFileName;
		worksImagePath = FolderUtils.getStoragePath(worksImagePrefix, works.getPassportId()) + worksSystemFileName;
		worksThumbnailImagePath = FolderUtils.getStoragePath(worksImagePrefix, works.getPassportId()) + worksThumbnailImageSystemFileName;
		
		int A4PageWorksBoxWidth = 0;	// 缩放至 A4 页面作品框宽度
		int A4PageWorksBoxHeight = 0;	// 缩放至 A4 页面作品框高度
		
		String pictureSize = null; 	// 图片尺寸（内框尺寸）
		String pictureSize2 = null; 	// 图片尺寸（内框尺寸）
		
		try {
			pictureSize = this.skuDao.selectPictureSizeByCode(works.getSkuCode());
			if(StringUtils.isNotBlank(skuCode2)) {
				pictureSize2 = this.skuDao.selectPictureSizeByCode(skuCode2);
			}
		} catch (Exception e) {
			LOGGER.error("根据【编号】查询【普通尺寸】 - 失败！", e);
			
			responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
			responseResult.setMessage("根据【编号】查询【普通尺寸】 - 失败！");
			
			return responseResult;
		}
		
		if(StringUtils.isBlank(pictureSize) || StringUtils.isBlank(pictureSize2)) {
			responseResult.setStatus(Constants.ACTION_STATUS_RESULT_EMPTY);
			responseResult.setMessage("未找到的【作品尺寸】！");
			
			return responseResult;
		}
		
		String worksSize_ [] = pictureSize.split("X");
		String worksSize2 [] = new String[2];
		if(StringUtils.isNotBlank(pictureSize2)) {
			worksSize2 = pictureSize2.split("X");
		}
		int worksSizeWidth = 0;	// 单位：像素
		int worksSizeHeight = 0;	// 单位：像素
		int worksSizeWidth2 = 0;	// 单位：像素
		int worksSizeHeight2 = 0;	// 单位：像素
		
		if(0 < worksSize_.length) {
			worksSizeWidth = Integer.parseInt(worksSize_[0]);
		}
		if(0 < worksSize_.length) {
			worksSizeHeight = Integer.parseInt(worksSize_[1]);
		}
		if(StringUtils.isNotBlank(worksSize2[0])) {
			worksSizeWidth2 = Integer.parseInt(worksSize2[0]);
		}
		if(StringUtils.isNotBlank(worksSize2[1])) {
			worksSizeHeight2 = Integer.parseInt(worksSize2[1]);
		}
		
		if(0 == worksSizeWidth || 0 == worksSizeHeight){
			responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
			responseResult.setMessage("【作品尺寸】有误！");
			
			return responseResult;
		}
		
		if(0 == width && 0 == height){	// 默认编辑
			
			// 由 毫米 转换为 像素
			worksSizeWidth = PdfUtil.millimeter2pixel_150ppi(worksSizeWidth);		
			worksSizeHeight = PdfUtil.millimeter2pixel_150ppi(worksSizeHeight);
			LOGGER.debug("worksSizeWidth = {}, worksSizeHeight = {}", worksSizeWidth, worksSizeHeight);
			
			int orginalImageWidth = ImageUtil.getImageWidth(orignalImagePath);	// 原图宽度
			int orginalImageHeight = ImageUtil.getImageHeight(orignalImagePath);	// 原图高度
			LOGGER.debug("orginalImageWidth = {}, orginalImageHeight = {}", orginalImageWidth, orginalImageHeight);
			
			int targetWidth = (int) ( (float) orginalImageWidth * (float) worksSizeHeight / (float) orginalImageHeight ); 	// 按高缩放
			int targetHeight = (int) ( (float) orginalImageHeight * (float) worksSizeWidth / (float) orginalImageWidth );	// 按宽缩放
			LOGGER.debug("targetWidth = {}, targetHeight = {}", targetWidth, targetHeight);
			
			LOGGER.debug("================== 第一步：缩放  ================");
			boolean isZoomSuccess = true;	// 是否缩放成功
			if(targetWidth >= worksSizeWidth) {	// 按框型的高度缩放
				abscissa = (targetWidth - worksSizeWidth) / 2;
				ordinate = 0;
				
				isZoomSuccess = ImageUtil.zoomImage(orignalImagePath, scaledImagePath, null, worksSizeHeight);
				
				if(!isZoomSuccess){
					responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
					responseResult.setMessage("默认缩放至框型的高度 - 失败！");
					
					return responseResult;
				}
			} else if(targetHeight >= worksSizeHeight) {	// 按框型的宽度缩放
				abscissa = 0;
				ordinate = (targetHeight - worksSizeHeight) / 2;
				
				isZoomSuccess = ImageUtil.zoomImage(orignalImagePath, scaledImagePath, worksSizeWidth, targetHeight);	// 兼容 CentOS 和 Windows
				
				if(!isZoomSuccess){
					responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
					responseResult.setMessage("默认缩放至框型的宽度 - 失败！");
					
					return responseResult;
				}
			}
			
			// 第二步：裁切
			LOGGER.debug("================== 第二步：裁剪  ================");
			LOGGER.debug("以左上角为原点，从横坐标：{}，纵坐标：{} 开始裁切，裁切宽度为：{} 像素，裁切高度为：{} 像素。", abscissa, ordinate, worksSizeWidth, worksSizeHeight);
			boolean isCutSuccess = ImageUtil.cutImage(scaledImagePath, cutedImagePath, abscissa, ordinate, worksSizeWidth, worksSizeHeight);
			
			if(!isCutSuccess){
				responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
				responseResult.setMessage("默认裁切图片 - 失败！");
				
				return responseResult;
			}
			
			A4PageWorksBoxWidth = (int) ( (float) worksSizeWidth * (float) WORKS_BOX_HEIGHT / (float) worksSizeHeight ); 	// 按高缩放
			A4PageWorksBoxHeight = (int) ( (float) worksSizeHeight * (float) WORKS_BOX_WIDTH / (float) worksSizeWidth );	// 按宽缩放
			LOGGER.debug("targetWidth = {}, targetHeight = {}", targetWidth, targetHeight);
			
			materialEdit.setWidth(worksSizeWidth);
			materialEdit.setHeight(worksSizeHeight);
		} else {	// 会员编辑
			LOGGER.debug("================== 第一步：旋转  ================");
			boolean isRotateSuccess = ImageUtil.rotate(orignalImagePath, rotatedImagePath, rotate);
			if(isRotateSuccess) {
				materialEdit.setEditedMaterialPath(rotatedImagePath);
				
				LOGGER.debug("以原图为基准，旋转 {} 度 - 成功。", rotate);
			}
			
			LOGGER.debug("================== 第二步：裁剪  ================");
			LOGGER.debug("以左上角为原点，从横坐标为：{}，纵坐标为：{} 开始裁切，裁切宽度为：{} 像素，裁切高度为：{} 像素。", abscissa, ordinate, (int) (width * scale), (int) (height * scale));
			
			int widthDifference = worksSizeWidth2 - worksSizeWidth;		// 不同 SKU 尺寸之间的差值，单位：像素
			int heightDifference = worksSizeHeight2 - worksSizeHeight;		// 不同 SKU 尺寸之间的差值，单位：像素
			
			if(0 > widthDifference){
				widthDifference = -PdfUtil.millimeter2pixel_150ppi(-widthDifference);
			} else {
				widthDifference = PdfUtil.millimeter2pixel_150ppi(widthDifference);
			}
			if(0 > heightDifference){
				heightDifference = -PdfUtil.millimeter2pixel_150ppi(-heightDifference);
			} else {
				heightDifference = PdfUtil.millimeter2pixel_150ppi(heightDifference);
			}
			
			abscissa = (int) (abscissa * scale - widthDifference / 2);		// 横坐标
			ordinate = (int) (ordinate * scale - heightDifference / 2);		// 纵坐标
			int cutWidth = (int) (width * scale + widthDifference);		// 裁切的宽度
			int cutHeight = (int) (height * scale + heightDifference);	// 裁切的高度
			
			boolean isCutSuccess = ImageUtil.cutImage(rotatedImagePath, cutedImagePath, abscissa, ordinate, cutWidth, cutHeight);
			
			if(!isCutSuccess){
				responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
				responseResult.setMessage("按会员编辑裁切图片 - 失败！");
				
				return responseResult;
			}
			
			int cutedImageWidth = ImageUtil.getImageWidth(cutedImagePath);
			int cutedImageHeight = ImageUtil.getImageHeight(cutedImagePath);
			
			A4PageWorksBoxWidth = (int) ( (float) cutedImageWidth * (float) WORKS_BOX_HEIGHT / (float) cutedImageHeight ); 	// 按高缩放
			A4PageWorksBoxHeight = (int) ( (float) cutedImageHeight * (float) WORKS_BOX_WIDTH / (float) cutedImageWidth );	// 按宽缩放
			LOGGER.debug("targetWidth = {}, targetHeight = {}", A4PageWorksBoxWidth, A4PageWorksBoxHeight);
			
			materialEdit.setWidth(cutedImageWidth);
			materialEdit.setHeight(cutedImageHeight);
		}
		
		boolean isZoomSuccess = true;	// 是否缩放成功
		
		LOGGER.debug("================== 第三步：缩放以适应 A4 纸张  ================");
		if(A4PageWorksBoxWidth > WORKS_BOX_WIDTH) {	// 按 A4 纸张高度缩放
			LOGGER.debug("以固定宽度 {} 为基准缩放图片；缩放后的作品图片路径 {}", WORKS_BOX_WIDTH, worksImagePath);
			isZoomSuccess = ImageUtil.zoomImage(cutedImagePath, worksImagePath, WORKS_BOX_WIDTH, null);
			if(!isZoomSuccess) {
				responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
				responseResult.setMessage("以宽为基准，制作符合 A4 纸张作品框尺寸的作品图 - 失败！");
				
				return responseResult;
			}
			
			cutedImagePath = worksImagePath;
			
			LOGGER.debug("================== 第四步：制作作品缩略图  ================");
			isZoomSuccess = ImageUtil.zoomImage(cutedImagePath, worksThumbnailImagePath, 200, null);	// 创建作品的缩略图
			if(!isZoomSuccess){
				responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
				responseResult.setMessage("以宽为基准，制作作品缩略图 - 失败！");
				
				return responseResult;
			}
		} else if(A4PageWorksBoxHeight > WORKS_BOX_HEIGHT) {	// 按 A4 纸张宽度缩放
			LOGGER.debug("以固定高度 {} 为基准缩放图片；缩放后的作品图片路径 {}", WORKS_BOX_HEIGHT, worksImagePath);
			isZoomSuccess = ImageUtil.zoomImage(cutedImagePath, worksImagePath, null, WORKS_BOX_HEIGHT);
			if(!isZoomSuccess) {
				responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
				responseResult.setMessage("以高为基准，制作符合 A4 纸张作品框尺寸的作品图 - 失败！");
				
				return responseResult;
			}
			
			cutedImagePath = worksImagePath;
			
			LOGGER.debug("================== 第四步：制作作品缩略图  ================");
			isZoomSuccess = ImageUtil.zoomImage(cutedImagePath, worksThumbnailImagePath, null, 200);	// 创建作品的缩略图
			if(!isZoomSuccess){
				responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
				responseResult.setMessage("以高为基准，制作作品缩略图 - 失败！");
				
				return responseResult;
			}
		}
		
		LOGGER.debug("================== 第五步：更新“作品图片”访问权限  ================");
		if(OperationSystemInfo.isLinux()) {
			boolean isUpdateFileAuthoritySuccess = ChmodShell.updateFileAuthority(cutedImagePath, 775);
			if(isUpdateFileAuthoritySuccess) {
				materialEdit.setEditedMaterialPath(cutedImagePath);
			}
			
			isUpdateFileAuthoritySuccess = ChmodShell.updateFileAuthority(worksThumbnailImagePath, 775);
			if(isUpdateFileAuthoritySuccess){
				works.setThumbnailPath(worksThumbnailImagePath);
			}
		} else if(OperationSystemInfo.isWindows()) {
			materialEdit.setEditedMaterialPath(cutedImagePath);
			works.setThumbnailPath(worksThumbnailImagePath);
		}
		
		return responseResult;
	}
}
